﻿using AutoMapper;
using D.B.Data.API.Applications.Command;
using D.B.Data.Common;
using D.B.Data.Domain;
using D.B.Data.Domain.DTO.Input;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace D.B.Data.API.Applications.CommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<LoginDTO>>
    {
        private readonly IBaseRepository<UserModel> _repository;
        private readonly IBaseRepository<RoleModel> _Rolepository;
        private readonly IBaseRepository<UserRoleModel> _userrolepository;
        private readonly JwtTools jwtTools;
        private readonly IConfiguration _configuration;

        private readonly IMapper mapper;

        public LoginCommandHandler(IBaseRepository<UserModel> repository, IMapper mapper, IBaseRepository<RoleModel> rolepository, IBaseRepository<UserRoleModel> userrolepository, JwtTools jwtTools, IConfiguration configuration)
        {
            _repository = repository;
            this.mapper = mapper;
            _Rolepository = rolepository;
            _userrolepository = userrolepository;
            this.jwtTools = jwtTools;
            _configuration = configuration;
        }

        public Task<APIResult<LoginDTO>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var res = _repository.GetAll().AsNoTracking().FirstOrDefault(s => s.UserName == request.UserName && s.UserPass == request.UserPass && !s.IsDel);
            

            APIResult<LoginDTO> result = new APIResult<LoginDTO>();
            if (res==null)
            {
                result.Code = EnumCode.File;
                result.Msg = "登陆失败";
                return Task.FromResult(result);
            }

            var roleId = _userrolepository.GetAll().AsNoTracking().Where(s => s.UserId == res.Id).Select(s => s.RoleId).ToList();
            //比对角色表中是否被删除
            var isRoleId = _Rolepository.GetAll().Where(s => roleId.Contains(s.Id) && !s.IsDel).Select(s => s.Id).ToList();
            var model = mapper.Map<LoginDTO>(res);

            
            model.RoleId = isRoleId;


            result.JWT = jwtTools.JwtNewString(_configuration, res.Id.ToString(), model);
            result.Code = EnumCode.Ok;
            result.Msg = "登陆成功";
            result.Data = model;
            return Task.FromResult(result);

        }
    }
}
